//
//  ImageDownloader.m
//  UI-17-图片异步下载
//
//  Created by lanou3g on 15/8/30.
//  Copyright (c) 2015年 自由科技. All rights reserved.
//

#import "ImageDownloader.h"

@implementation ImageDownloader
//封装异步下载图片
+ (UIImage *)sychronousDownloader:(NSString *)imgURL{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:imgURL]];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    return [UIImage imageWithData:data];
}

//封装异步下载图片(代理传值)
+(void)asendAsynchronousDownloader:(NSString *)imgURL andDelegate:(id<DownloaderDelegate>)delegate{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:imgURL]];
    //
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *img = [UIImage imageWithData:data];
        //block里面的值无法直接返回,需要借助代理将值串出去
        //在值传递之前,我们必须保证代理是否存在,以及它响应代理方法
        if (delegate != nil && [delegate respondsToSelector:@selector(downloaderDidFinishDownloadImg:)]) {
            [delegate downloaderDidFinishDownloadImg:img];
        }
    }];
}
//block传值
+(void)asendAsynchronousDownloader:(NSString *)imgURL andBlock:(BLOCK)block{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:imgURL]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *img = [UIImage imageWithData:data];
        //调用block 方式和代理一样,都是把数据作为参数传出去
        block(img);
    }];
    
    
}


//动态方法
//代理
- (void)delegateAsendAsynchronousDownloader:(NSString *)imgURL{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:imgURL]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *img = [UIImage imageWithData:data];
        if (_delegate != nil && [_delegate respondsToSelector:@selector(downloaderDidFinishDownloadImg:)]) {
            [_delegate downloaderDidFinishDownloadImg:img];
        }
    }];
}
//block
- (void)blockAsendAsynchronousDownloader:(NSString *)imgURL{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:imgURL]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *img = [UIImage imageWithData:data];
        _block(img);
    }];
}


@end
